import React, { useState, useEffect, useCallback } from 'react';
import { Layout, Menu, theme } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  AppstoreOutlined,
  DashboardOutlined,
  TableOutlined,
  SettingOutlined,
  UserOutlined,
  TeamOutlined,
  BranchesOutlined,
  SafetyOutlined,
  DatabaseOutlined,
  LineChartOutlined,
  BarChartOutlined,
  PieChartOutlined,
  FileTextOutlined,
  FolderOutlined,
  CloudOutlined,
  ApiOutlined,
  MonitorOutlined,
  ToolOutlined,
  SecurityScanOutlined,
  AuditOutlined,
  ProfileOutlined,
  ContactsOutlined,
  GlobalOutlined,
  HomeOutlined,
  MenuOutlined,
  ControlOutlined,
  DeploymentUnitOutlined,
  ClusterOutlined,
  NodeIndexOutlined,
  PartitionOutlined,
  SyncOutlined,
  ScheduleOutlined,
  HistoryOutlined,
} from '@ant-design/icons';
import { useAuth } from '../../contexts/AuthContext';
import { useTheme } from '../../contexts/ThemeContext';
import { menuService, MenuItem } from '../../services/menuService';
import { showNotification } from '../../utils/notification';
import { usePermissionSync } from '../../hooks/usePermissionSync';

const { Sider } = Layout;

// 图标映射
const sidebarIconMap: Record<string, React.ComponentType> = {
  DashboardOutlined,
  TableOutlined,
  SettingOutlined,
  UserOutlined,
  TeamOutlined,
  AppstoreOutlined,
  BranchesOutlined,
  SafetyOutlined,
  DatabaseOutlined,
  LineChartOutlined,
  BarChartOutlined,
  PieChartOutlined,
  FileTextOutlined,
  FolderOutlined,
  CloudOutlined,
  ApiOutlined,
  MonitorOutlined,
  ToolOutlined,
  SecurityScanOutlined,
  AuditOutlined,
  ProfileOutlined,
  ContactsOutlined,
  GlobalOutlined,
  HomeOutlined,
  MenuOutlined,
  ControlOutlined,
  DeploymentUnitOutlined,
  ClusterOutlined,
  NodeIndexOutlined,
  PartitionOutlined,
  SyncOutlined,
  ScheduleOutlined,
  HistoryOutlined,
};

interface SidebarProps {
  collapsed: boolean;
}

const Sidebar: React.FC<SidebarProps> = ({ collapsed }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const { hasPermission } = useAuth();
  const { currentTheme } = useTheme();
  const {
    token: { colorBgContainer },
  } = theme.useToken();

  // 菜单状态
  const [menuItems, setMenuItems] = useState<MenuItem[]>([]);
  const [loading, setLoading] = useState(true);

  // 加载菜单函数 - 优化版本
  const loadMenu = useCallback(async (forceRefresh = false) => {
    try {
      setLoading(true);


      const items = await menuService.getUserMenu(forceRefresh);
      const filteredItems = menuService.filterMenuByPermissions(items, hasPermission);



      setMenuItems(filteredItems);
    } catch (error) {
      console.error('加载菜单失败:', error);
      showNotification('error', '菜单加载失败', '请刷新页面重试');
      setMenuItems([]); // 设置为空数组，不使用默认菜单
    } finally {
      setLoading(false);
    }
  }, [hasPermission]);

  // 权限同步Hook - 优化版本
  usePermissionSync({
    onPermissionChange: () => {
      // 权限变更时强制重新加载菜单

      loadMenu(true); // 强制刷新
    },
    autoRefreshMenu: false, // 手动控制菜单刷新
    debug: process.env.NODE_ENV === 'development'
  });

  // 获取动态菜单（优化版本）- 只在组件挂载时加载一次
  useEffect(() => {

    loadMenu();
  }, []); // 移除loadMenu依赖，避免不必要的重新加载

  // 转换菜单项为Ant Design Menu所需的格式 - 修复图标处理并添加错误保护
  const convertMenuItems = (items: MenuItem[]): any[] => {
    return items.map(item => {
      let iconElement = undefined;

      // 处理图标 - 现在item.icon存储的是图标名称字符串
      if (item.icon) {
        const iconName = item.icon as string;
        const IconComponent = sidebarIconMap[iconName];



        if (IconComponent) {
          iconElement = React.createElement(IconComponent);

        } else {

          // 使用默认图标
          iconElement = React.createElement(AppstoreOutlined);
        }
      } else {

        // 使用默认图标
        iconElement = React.createElement(AppstoreOutlined);
      }

      return {
        key: item.key,
        icon: iconElement,
        label: item.label,
        children: item.children ? convertMenuItems(item.children) : undefined,
      };
    });
  };

  const handleMenuClick = ({ key }: { key: string }) => {
    // 处理仪表盘路径：当点击菜单中的 / 时，导航到 /dashboard
    if (key === '/') {
      navigate('/dashboard');
    } else {
      navigate(key);
    }
  };

  // 获取当前选中的菜单项 - 修复仪表盘路径匹配问题
  const getSelectedKeys = () => {
    const currentPath = location.pathname;

    // 处理仪表盘路径匹配：当访问 /dashboard 时，选中菜单中的 / 项
    if (currentPath === '/dashboard') {
      return ['/'];
    }

    return [currentPath];
  };

  // 获取当前展开的菜单项
  const getOpenKeys = () => {
    const pathSegments = location.pathname.split('/');
    const openKeys: string[] = [];

    for (let i = 1; i < pathSegments.length; i++) {
      const key = '/' + pathSegments.slice(1, i + 1).join('/');
      // 检查是否是父级菜单
      const hasChildren = menuItems.some((item: MenuItem) =>
        item.children && item.children.some((child: MenuItem) => child.key.startsWith(key))
      );
      if (hasChildren) {
        openKeys.push(key);
      }
    }

    return openKeys;
  };

  // 转换后的菜单项 - 添加调试信息
  const antdMenuItems = React.useMemo(() => {

    return convertMenuItems(menuItems);
  }, [menuItems]);

  return (
    <Sider
      trigger={null}
      collapsible
      collapsed={collapsed}
      style={{
        background: colorBgContainer,
        position: 'fixed',
        left: 0,
        top: 0,
        bottom: 0,
        zIndex: 200,
        height: '100vh',
        overflow: 'auto',
      }}
      width={280}
      collapsedWidth={80}
    >
      <div
        style={{
          height: 80,
          margin: '20px 16px',
          background: 'linear-gradient(135deg, rgba(79, 70, 229, 0.1) 0%, rgba(99, 102, 241, 0.1) 100%)',
          borderRadius: 16,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: collapsed ? 18 : 24,
          fontWeight: 700,
          color: '#4f46e5',
          position: 'relative',
          overflow: 'hidden',
          transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
          cursor: 'pointer',
          border: '2px solid rgba(79, 70, 229, 0.1)',
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.transform = 'scale(1.02)';
          e.currentTarget.style.boxShadow = '0 8px 25px rgba(79, 70, 229, 0.15)';
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.transform = 'scale(1)';
          e.currentTarget.style.boxShadow = 'none';
        }}
      >
        <div
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            background: 'linear-gradient(45deg, transparent 30%, rgba(255, 255, 255, 0.1) 50%, transparent 70%)',
            transform: 'translateX(-100%)',
            transition: 'transform 0.6s ease',
          }}
          className="logo-shimmer"
        />
        <div style={{ position: 'relative', zIndex: 1 }}>
          {collapsed ? (
            <div style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: 2
            }}>
              <div style={{ fontSize: 20, fontWeight: 800 }}>D</div>
              <div style={{ fontSize: 20, fontWeight: 800 }}>P</div>
            </div>
          ) : (
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: 8
            }}>
              <div style={{
                width: 32,
                height: 32,
                borderRadius: '50%',
                background: 'linear-gradient(135deg, #4f46e5 0%, #6366f1 100%)',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#fff',
                fontSize: 16,
                fontWeight: 700,
                boxShadow: '0 4px 12px rgba(79, 70, 229, 0.3)',
              }}>
                D
              </div>
              <span style={{
                background: 'linear-gradient(135deg, #4f46e5 0%, #6366f1 100%)',
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
                backgroundClip: 'text',
                fontSize: 22,
                fontWeight: 800,
                letterSpacing: '-0.5px'
              }}>
                DataPlexus
              </span>
            </div>
          )}
        </div>
      </div>
      {loading ? (
        <div style={{
          padding: '20px',
          textAlign: 'center',
          color: '#666'
        }}>
          加载菜单中...
        </div>
      ) : menuItems.length === 0 ? (
        <div style={{
          padding: '20px',
          textAlign: 'center',
          color: '#999'
        }}>
          暂无可用菜单
        </div>
      ) : (
        <Menu
          mode="inline"
          selectedKeys={getSelectedKeys()}
          defaultOpenKeys={getOpenKeys()}
          items={antdMenuItems}
          onClick={handleMenuClick}
          style={{ borderRight: 0 }}
        />
      )}
    </Sider>
  );
};

export default Sidebar;
